package com.situ.filter;

import com.situ.pojo.User;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;
import java.nio.file.PathMatcher;

@WebFilter("/*")
public class LoginFilter implements Filter {
    public static final String[] WHITE={"/admin/login/**","/assets/**","/admin/captcha/**","/admin/logout/**"};
    public static final String LOGIN_USER_KEY="@login_user";
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        HttpServletResponse resp=(HttpServletResponse)servletResponse;
        String requestURI = req.getRequestURI();
        System.out.println(requestURI);
        requestURI=requestURI.replace(req.getContextPath(),"");
        //路径匹配器
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String patten : WHITE) {
            if(antPathMatcher.match(patten,requestURI)){
                //匹配成功则放行
                filterChain.doFilter(req,resp);
                return;
            }
        }


        //会话域
        HttpSession session = req.getSession();
        System.out.println(session.getId());
        User user=(User) session.getAttribute(LOGIN_USER_KEY);
        if(user==null){
            //未登录
            resp.sendRedirect(req.getContextPath()+"/admin/login");
        }else {
            //登录则放行----让别的过滤器去继续处理
            filterChain.doFilter(req,resp);
        }
    }
}
